import React, { useState, useEffect } from "react";
import "./ChatRoom.css";

interface ChatMessage {
  author: string;
  message: string;
  timestamp: number;
}

const ChatRoom: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState("");

  useEffect(() => {
    // 这里可以模拟从服务器获取实时消息
    const intervalId = setInterval(() => {
      const randomAuthor = ["机器人", "阿里云客服"][Math.floor(Math.random() * 2)];
      const randomMessage = Math.random().toString(36).substring(7);
      const newTimestamp = Date.now();

      setMessages((prevMessages) =>
        [...prevMessages, { author: randomAuthor, message: randomMessage, timestamp: newTimestamp }]
      );
    }, 10000);

    return () => clearInterval(intervalId); // 清除定时器以避免内存泄漏
  }, []);

  const handleSendButtonClicked = () => {
    if (!newMessage.trim()) return;

    const newTimestamp = Date.now();
    setMessages((prevMessages) => [...prevMessages, { author: "我", message: newMessage, timestamp: newTimestamp }]);
    setNewMessage("");
  };

  return (
    <div className="chat-room">
      <div className="message-list">
        {messages.map((message, index) => (
          <div key={index} className={`message ${message.author === "我" ? "sent-message" : "received-message"}`}>
            <span className="author">{message.author}: </span>
            <span className="content">{message.message}</span>
            <span className="timestamp">{new Date(message.timestamp).toLocaleString()}</span>
          </div>
        ))}
      </div>
      <div className="input-container">
        <textarea
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          placeholder="请输入消息"
          rows={4}
        />
        <button onClick={handleSendButtonClicked}>发送</button>
      </div>
    </div>
  );
};

export default ChatRoom;